package com.hashnode.firstboot.controller;

import com.hashnode.firstboot.model.BookInfo;
import com.hashnode.firstboot.service.BookService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class BookController {


    @Autowired
    private BookService bookService;

    @GetMapping("/")
    public String index(Model model){
        model.addAttribute("tip","欢迎访问第一个Spring Boot应用");
        return "hello";
    }

    @GetMapping("/rest")
    @ResponseBody
    public ResponseEntity restIndex(){
//        return new ResponseEntity<>("欢迎访问第一个Spring Boot应用",null, HttpStatus.OK);    欢迎访问第一个Spring Boot应用
        BookInfo bookInfo = new BookInfo();
        bookInfo.setId(1);
        bookInfo.setAuthor("aaa");
        return new ResponseEntity<>(bookInfo,null, HttpStatus.OK);
        /*
            {
            "id": 1,
            "title": null,
            "author": "aaa",
            "price": null
            }
         */
    }

    @PostMapping("/addBook")
    public String addBook(BookInfo book,Model model){
        bookService.addBook(book);
        return "redirect:listBooks";
    }

    @GetMapping("/listBooks")
    public String list(Model model){
        model.addAttribute("books",bookService.getAllBooksInfo());
        return "list";
    }

    @GetMapping("/deleteBook")
    public String delete(Integer id){
        bookService.deleteBook(id);
        return "redirect:listBooks";
    }

    @DeleteMapping("rest/books/del/{id}")
    @ResponseBody
    public ResponseEntity<Map<String,String>> restDelete(@PathVariable Integer id){
        bookService.deleteBook(id);
        Map<String, String> map = new HashMap<String, String>();
        map.put("tip","删除成功");
        return new ResponseEntity<>(map,null,HttpStatus.OK);
    }

}
